'use client';

import {usePathname} from 'next/navigation';
import {useRouter} from 'next-nprogress-bar';
import {useCallback, useMemo} from 'react';

export const normalizePath = (path: string) => {
    if (path.startsWith('/')) {
        return path;
    }
    return '/' + path;
};

export function getPathList(pathname: string) {
    const normalPathname = pathname.replace(/^\//, '');
    if (!normalPathname) return [];
    return normalPathname.split('/') || [];
}
export function getPathItem(pathname: string, level: number) {
    const pathList = getPathList(pathname);
    return pathList[level];
}

export function usePathLevel(level: number) {
    const pathname = usePathname();
    const currentPath = useMemo<string>(() => {
        return getPathItem(pathname, level);
    }, [pathname, level]);

    return {currentPath};
}

export function useQueryToActive() {
}

export function useJump() {
    const router = useRouter();
    const pathname = usePathname();

    const jump = useCallback((path: string, options?: {level?: number, keepQuery?: boolean}) => {
        const pathList = getPathList(pathname);
        const {level} = options || {};

        if (level === undefined) {
            return router.push(normalizePath(path));
        }
        pathList.splice(Math.min(level, pathList.length), 1, path);
        return router.push(normalizePath(pathList.join('/')));
    }, [pathname, router]);

    return {jump};
}
